/*
* Copyright© 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.netty.server.server;

import com.laihuichuxing.netty.common.core.model.Request;
import com.laihuichuxing.netty.common.core.session.Session;
import com.laihuichuxing.netty.common.core.session.SessionImpl;
import com.laihuichuxing.netty.common.core.session.SessionManager;
import com.laihuichuxing.netty.server.server.module.login.entity.Login;
import com.laihuichuxing.netty.server.server.scanner.Invoker;
import com.laihuichuxing.netty.server.server.scanner.InvokerHoler;
import com.laihuichuxing.socket.LoginCmd;
import com.laihuichuxing.socket.ModuleId;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description: 消息处理类
 *
 * @author YangGuang
 * @since: 1.0
 * Create Date Time: 2018/7/4 17:48
 * Update Date Time:
 * @see
 */
public class ServerHandler extends SimpleChannelInboundHandler<Request> {

    private Logger logger = LoggerFactory.getLogger(ServerHandler.class);

    /**
     * 接收消息
     *
     * @param ctx
     * @param request
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request request) throws Exception {
        handlerMessage(new SessionImpl(ctx.channel()), request,ctx);
    }

    /**
     * 心跳
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.ALL_IDLE) {
                //清除超时会话
                logger.info("Timeout disconnect");
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        if (!channel.isActive()) {
            channel.close();
        }
    }

    /**
     * 断线移除会话
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().close();
        Session session = new SessionImpl(ctx.channel());
        removeSession(session);
    }

    /**
     * 捕获异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("server exception:{}",cause);
        if(ctx.channel().isActive()) {
            ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
        ctx.channel().close();
    }

    /**
     * 移除会话
     *
     * @param session
     */
    private void removeSession(Session session) {
        Object object = session.getAttachment();
        if (object != null) {
            Login login = (Login) object;
            logger.info("手机号:{}的用户下线了",login.getMobile());
            SessionManager.removeSession(login.getMobile());
        }
    }

    /**
     * 消息处理
     */
    private void handlerMessage(Session session, Request request, ChannelHandlerContext ctx) {
        Object object = session.getAttachment();
        String mobile="";
        if (object != null) {
            Login login = (Login) object;
            mobile= login.getMobile();
        }
        short module = request.getModule();
        short cmd = request.getCmd();
        if (module == ModuleId.LOGIN && cmd == LoginCmd.HEART_BEAT) {
            // 心跳不处理
            logger.info("手机号:{}发送心跳,当前时间戳:{}",mobile,System.currentTimeMillis());
        } else {
            //获取命令执行器
            Invoker invoker = InvokerHoler.getInvoker(module, cmd);
            if (invoker != null) {
                // 执行命令

                try {
                    if (module == 1 && cmd == 1) {
                        invoker.invoke(session, request.getData(),ctx.channel());
                    } else {
                        invoker.invoke(session, request.getData());
                    }
                } catch (Exception e) {
                    logger.error("消息处理异常:{}",e);
                }
            } else {
                return;
            }
        }
    }

}
